import {
  Catch,
  ExceptionFilter,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class CustomExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost): any {
    const ctx = host.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();
    const message = exception.message || 'Bad Request';
    const status = exception.getStatus?.() || 500;

    const reponseObj = {
      code: 1,
      data: {
        path: request.url,
        method: request.method,
        // requestQuery: request.query,
        // requestParam: request.params,
        // requestBody: request.body,
        timestamp: new Date().getTime(),
      },
      message,
    };
    // 拦截token不合法及过期(50014)
    if (status === 401 && message === 'Unauthorized') {
      reponseObj.code = 50014;
      reponseObj.message = '检测到您登录已过期，请重新登录！';
    }
    // 拦截token失效问题(50012)
    if (status === 401 && message === 'Other clients logged in') {
      reponseObj.code = 50012;
      reponseObj.message = '检测到您已在其他设备登录，请重新登录！';
    }

    //自定义返回结果
    response.status(200).json({
      ...reponseObj,
    });
  }
}
